package com.item.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.item.mapper.User1Mapper;
import com.item.pojo.User1;
import com.item.service.User1LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Map;


@Service
public class User1LoginServiceImpl implements User1LoginService {

    @Autowired
    private User1Mapper user1Mapper;

    private String appId = "wx1e27eacbaf5157db";
    private String appSecret = "7c1a54e6de9f6d39c00f47d19e90256c";


    @Override
    public User1 Update(Map map) {
        String openid=(String) map.get("openid");
        user1Mapper.update(map);
        return user1Mapper.findAll(openid);
    }


    @Override
    public String login(Map map) {
        User1 user = new User1();
        String openid=null;
        System.out.println(map);
        String code = (String) map.get("code");
        user.setImgUrl((String) map.get("imgUrl"));
        user.setNickName((String) map.get("nickName"));
        user.setGender((String)map.get("gender"));

        //微信服务器的接口路径
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        //进行网络请求,访问微信服务器接口
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
        if (responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK) {
            JSONObject jsonObject = JSONObject.parseObject(responseEntity.getBody());
            System.out.println(jsonObject);
            openid=jsonObject.getString("openid");
            user.setSessionKey(jsonObject.getString("session_key"));
            user.setOpenid(jsonObject.getString("openid"));
            if (user1Mapper.finduser(openid)==0) {
                int count = user1Mapper.insertuser(user);
                if (count == 1) {
                    System.out.println("插入成功");
                }
            }
        }
        return openid;
    }

    @Override
    public User1 person(String openid) {
        return user1Mapper.findAll(openid);
    }
}
